package cn.com.dpc.util;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.SearchManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.dpc.BaseListActivity;
import cn.com.dpc.DevListActivity;
import cn.com.dpc.R;
import cn.com.dpc.adapter.ColumnAdapter;
import cn.com.dpc.adapter.MixAdapter;
import cn.com.dpc.bean.Columnobject;

public class SearchResultActivity extends BaseListActivity {
	private TextView result = null;
	private String queryKeyword = "";
	private String sbStations = "";

	private ColumnAdapter columnAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.searchstations);

		ImageButton editButton = (ImageButton) findViewById(R.id.edit_button);
		editButton.setVisibility(View.INVISIBLE);
		ImageButton backButton = (ImageButton) findViewById(R.id.back_button);
		backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				doExit();
			}
		});

		TextView titleText = (TextView) findViewById(R.id.myTitle);
		titleText.setText("搜索结果");

		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			queryKeyword = intent.getStringExtra(SearchManager.QUERY);

			Bundle bundled = intent.getBundleExtra(SearchManager.APP_DATA);
			sbStations = bundled.getString("data");
			// saveRecentSearchHistory(queryKeyword);
			// doSearch(queryKeyword);
		}
		if (!queryKeyword.equals("")) {
			showList();
		}
	}

	private void showList() {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... arg0) {
				try {
					return true;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				closeProgressBar();
				if (result) {

					try {
						JSONArray jsonArray = new JSONArray(sbStations);

						columnAdapter = new MixAdapter(
								SearchResultActivity.this);

						List<Columnobject> list = new ArrayList<Columnobject>();
						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject jo = jsonArray.getJSONObject(i);
							String stationName = jo.getString("stationName");
							String reg = ".*";
							for (int j = 0; j < queryKeyword.length(); j++) {
								reg += queryKeyword.charAt(j) + ".*";
							}
							if (!stationName.matches(reg)) {
								continue;
							}
							Columnobject columnobject = new Columnobject();
							columnobject.setNumber(1);
							columnobject.setType(jo.getInt("stationNo"));
							columnobject.setUrl(jo.getString("stationNo"));
							columnobject.setTexts(stationName);
							list.add(columnobject);
						}
						changeObject(list, columnAdapter);
						setListAdapter(columnAdapter);
					} catch (Exception e) {
						// TODO: handle exception
					}
				} else {
					Toast.makeText(SearchResultActivity.this, "数据加载失败！",
							Toast.LENGTH_SHORT).show();
				}

			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showProgressBar();
			}

		}.execute();

	}

	private void changeObject(List<Columnobject> list,
			ColumnAdapter columnAdapter) {
		int[] number = new int[list.size()];
		int[] type = new int[list.size()];
		String[] url = new String[list.size()];
		String[] texts = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			Columnobject columnobject = list.get(i);
			number[i] = columnobject.getNumber();
			type[i] = columnobject.getType();
			url[i] = columnobject.getUrl();
			texts[i] = columnobject.getTexts();
		}
		columnAdapter.setNumber(number);
		columnAdapter.setType(type);
		columnAdapter.setUrl(url);
		columnAdapter.setTexts(texts);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = new Intent(SearchResultActivity.this,
				DevListActivity.class);
		intent.setFlags(1);
		Bundle bundle = new Bundle();
		bundle.putInt("stationId",
				Integer.parseInt(columnAdapter.getUrl()[position]));
		bundle.putString("stationName", columnAdapter.getTexts()[position]);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	// 保存最近搜索的关键字记录
	private void saveRecentSearchHistory(String queryKeyword) {
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				SearchSuggestionSampleProvider.AUTHORITY,
				SearchSuggestionSampleProvider.MODE);
		suggestions.saveRecentQuery(queryKeyword, null);
	}

	// 清除最近搜索的关键字记录
	private void clearRecentSearchHistory() {
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				SearchSuggestionSampleProvider.AUTHORITY,
				SearchSuggestionSampleProvider.MODE);
		suggestions.clearHistory();
	}

	private void doSearch(String queryKeyword) {
		result.setText("Your search keyword is : " + queryKeyword);
	}

	@Override
	protected void onDestroy() {
		// clearRecentSearchHistory();
		super.onDestroy();
	}

}
